Kotlin Koans 21 Filter; map

Contents

Filter; map (Playground)

Description

Implement extension functions Shop.getCitiesCustomersAreFrom() and Shop.getCustomersFrom() using functions map and filter.

mapとfilterを使用して、拡張関数Shop.getCitiesCustomersAreFrom()およびShop.getCustomersFrom()を実装してください。

val numbers = listOf(1, -1, 2)
numbers.filter { it > 0 } == listOf(1, 2)
numbers.map { it * it } == listOf(1, 1, 4)

Code

// Return the set of cities the customers are from
fun Shop.getCitiesCustomersAreFrom(): Set<City> = customers.map { it.city }.toSet()

// Return a list of the customers who live in the given city
fun Shop.getCustomersFrom(city: City): List<Customer> = customers.filter { it.city == city }

Memo

  • map ... 元のコレクションの各要素に、ラムダ内の処理を適用したListを返す。問題文の返り値の型はSet<City>なので、さらにtoSet()で変換する
  • filter ... ラムダ内の処理に一致する要素だけを含むListを返す

← Posts